import sys
import os
import logging
from pathlib import Path

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('app.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

def setup_qt_plugins():
    """设置Qt插件路径"""
    try:
        # 获取可能的插件路径
        possible_paths = [
            # PyInstaller打包后的路径
            Path(sys._MEIPASS) / 'PyQt5' / 'Qt5' / 'plugins' if hasattr(sys, '_MEIPASS') else None,
            Path(sys._MEIPASS) / 'platforms' if hasattr(sys, '_MEIPASS') else None,
            # 开发环境路径
            Path(sys.prefix) / 'Lib/site-packages/PyQt5/Qt5/plugins',
            Path.cwd() / 'plugins',
        ]
        
        # 过滤掉None值
        possible_paths = [p for p in possible_paths if p is not None]
        
        # 查找第一个存在的路径
        for plugin_path in possible_paths:
            if plugin_path.exists():
                os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = str(plugin_path)
                logger.info(f"设置Qt插件路径: {plugin_path}")
                return True

        logger.error(f"未找到Qt插件路径。尝试过的路径: {possible_paths}")
        return False
        
    except Exception as e:
        logger.error(f"设置Qt插件路径失败: {e}")
        return False

# 添加src目录到Python路径
project_root = Path(__file__).resolve().parent
sys.path.append(str(project_root))

# 必须在导入PyQt5之前设置插件路径
if not setup_qt_plugins():
    print("警告：无法找到Qt插件路径，程序可能无法正常运行")
    logger.warning("无法找到Qt插件路径，尝试继续运行...")

from PyQt5.QtWidgets import QApplication, QMessageBox
from PyQt5.QtGui import QIcon

# 导入自定义模块
try:
    from gui.window import MainWindow
except ImportError as e:
    logger.critical(f"无法导入gui.window模块: {e}")
    print(f"严重错误: 无法导入gui.window模块，可能是gui目录被误删除")
    sys.exit(1)
    
try:
    from services.image_processor import ImageProcessor
except ImportError as e:
    logger.critical(f"无法导入services.image_processor模块: {e}")
    print(f"严重错误: 无法导入services.image_processor模块，可能是services目录被误删除")
    sys.exit(1)

def ensure_directory_exists(dir_path: Path) -> bool:
    """确保目录存在，如果不存在则创建"""
    try:
        dir_path.mkdir(parents=True, exist_ok=True)
        logger.info(f"确保目录存在: {dir_path}")
        return True
    except Exception as e:
        logger.error(f"创建目录失败 {dir_path}: {e}")
        return False

# 检查环境是否满足运行条件
def check_environment() -> bool:
    """检查并确保运行环境满足要求"""
    try:
        # 要创建的必要文件夹
        required_dirs = ['resources', 'output']
        
        # 确保每个必要的文件夹都存在
        for dir_name in required_dirs:
            dir_path = Path(dir_name)
            if not ensure_directory_exists(dir_path):
                logger.error(f"无法创建必要的文件夹: {dir_name}")
                return False
                
        # 检查其他环境要求
        try:
            from PyQt5.QtCore import QT_VERSION_STR
            logger.info(f"Qt版本: {QT_VERSION_STR}")
            
            from PIL import __version__ as pil_version
            logger.info(f"Pillow版本: {pil_version}")
            
        except ImportError as e:
            logger.error(f"缺少必要的依赖: {e}")
            return False
            
        return True
        
    except Exception as e:
        logger.error(f"检查环境失败: {e}")
        return False

# 定义资源路径函数
def resource_path(relative_path: str) -> Path:
    """获取资源的绝对路径"""
    try:
        base_path = getattr(sys, '_MEIPASS', Path(__file__).parent)
        return Path(base_path) / relative_path
    except Exception as e:
        logger.error(f"获取资源路径失败: {e}")
        return Path(relative_path)

# 检查资源是否存在
def check_resources() -> bool:
    """检查必要的资源文件是否存在"""
    try:
        required_files = ['resources/icon.ico']
        for file_name in required_files:
            file_path = resource_path(file_name)
            if not file_path.exists():
                logger.error(f"缺少必要的资源文件: {file_name}")
                return False
        return True
    except Exception as e:
        logger.error(f"检查资源失败: {e}")
        return False

def check_file_structure() -> bool:
    """检查完整的文件结构是否正确"""
    try:
        # 检查必要的模块文件
        critical_files = [
            Path('gui/window.py'),
            Path('services/image_processor.py'),
            Path('resources/icon.ico')
        ]
        
        missing_files = [f for f in critical_files if not f.exists()]
        
        if missing_files:
            logger.error(f"缺失关键文件: {missing_files}")
            
            # 提供恢复建议
            if Path('gui/window.py') not in missing_files and Path('services/image_processor.py') in missing_files:
                logger.error("可能是 'services' 目录被误删除")
            elif Path('gui/window.py') in missing_files and Path('services/image_processor.py') not in missing_files:
                logger.error("可能是 'gui' 目录被误删除")
            
            return False
        
        return True
    except Exception as e:
        logger.error(f"检查文件结构失败: {e}")
        return False

def main() -> int:
    """程序主入口"""
    try:
        # 在创建QApplication之前检查环境
        if not check_environment():
            return 1
            
        # 添加文件结构检查
        if not check_file_structure():
            QMessageBox.critical(None, "文件结构错误", 
                                "程序关键文件缺失，请重新安装程序或恢复被删除的文件。")
            return 1

        app = QApplication(sys.argv)
            
        if not check_resources():
            return 1
        
        icon_path = resource_path('resources/icon.ico')
        if icon_path.exists():
            app.setWindowIcon(QIcon(str(icon_path)))

        window = MainWindow()
        window.show()
        
        logger.info("程序启动成功")
        return app.exec_()
        
    except Exception as e:
        logger.critical(f"程序崩溃: {str(e)}", exc_info=True)
        QMessageBox.critical(
            None,
            "致命错误",
            f"程序意外终止:\n{str(e)}\n详见日志文件：app.log"
        )
        return 1

if __name__ == "__main__":
    sys.exit(main())
